package com.pfzy.ui.activity.pick;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.pfzy.ui.R;
import com.pfzy.ui.activity.pick.adapter.ArrayWheelAdapter;
import com.pfzy.ui.activity.pick.adapter.NumericWheelAdapter;
import com.pfzy.ui.log.MyLog;
import com.pfzy.ui.utils.ChinaDate;
import com.pfzy.ui.utils.LunarCalendar;
import com.pfzy.ui.utils.PickerViewAnimateUtil;
import com.pfzy.ui.view.wheelview.WheelView;
import com.pfzy.ui.view.wheelview.listener.OnItemSelectedListener;

import java.util.Calendar;
import java.util.List;

public class PickerDlg3 extends Dialog implements View.OnClickListener {
    private ViewGroup dialogView;// 附加Dialog 的 根View
    private ViewGroup contentContainer;
    private Dialog mDialog;
    private Animation outAnim;
    private Animation inAnim;
    private int animGravity = Gravity.BOTTOM;
    private int gravity = Gravity.CENTER;
    private int textSize = 18;
    private float lineSpacingMultiplier = 1.6f; // 条目间距倍数 默认1.6
    private int textColorOut = 0xFFa8a8a8; // 分割线以外的文字颜色
    private int textColorCenter = 0xFF2a2a2a; // 分割线之间的文字颜色
    private boolean isCenterLabel = false;// 是否只显示中间的label,默认每个item都显示
    private Calendar date;//当前选中时间
    private int startYear = PickerConst.DEFAULT_START_YEAR;
    private int endYear = PickerConst.DEFAULT_END_YEAR;
    private int startMonth = PickerConst.DEFAULT_START_MONTH;
    private int endMonth = PickerConst.DEFAULT_END_MONTH;
    private int startDay = PickerConst.DEFAULT_START_DAY;
    private int endDay = PickerConst.DEFAULT_END_DAY; //表示31天的
    private WheelView wv_year;
    private WheelView wv_month;
    private WheelView wv_day;
    private WheelView wv_hours;
    private WheelView wv_minutes;
    private WheelView wv_seconds;

    public PickerDlg3(@NonNull Context context) {
        super(context);
        initWindow();
        initAnim();
        initView();
    }

    private void initWindow() {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        // 如果是对话框模式
        dialogView = (ViewGroup) layoutInflater.inflate(R.layout.layout_basepickerview, null, false);
        // 设置界面的背景为透明
        dialogView.setBackgroundColor(Color.TRANSPARENT);
        // 这个是真正要加载选择器的父布局
        contentContainer = dialogView.findViewById(R.id.content_container);
        // 设置对话框 默认左右间距屏幕30
        params.leftMargin = 30;
        params.rightMargin = 30;
        contentContainer.setLayoutParams(params);

        // 创建对话框
        createDialog();
        //给背景设置点击事件,这样当点击内容以外的地方会关闭界面
        dialogView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    protected void initAnim() {
        inAnim = getInAnimation();
        outAnim = getOutAnimation();
    }

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.dlg_picker_3, contentContainer);
        // 确定和取消按钮
        Button btnSubmit = contentContainer.findViewById(R.id.dlg_picker_3_btn);
        ImageView btnCancel = contentContainer.findViewById(R.id.dlg_picker_3_close);
        btnSubmit.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        wv_year = contentContainer.findViewById(R.id.dlg_picker_3_year);
        wv_month = contentContainer.findViewById(R.id.dlg_picker_3_month);
        wv_day = contentContainer.findViewById(R.id.dlg_picker_3_day);
        wv_hours = contentContainer.findViewById(R.id.dlg_picker_3_hour);
        wv_minutes = contentContainer.findViewById(R.id.dlg_picker_3_minute);
        wv_seconds = contentContainer.findViewById(R.id.dlg_picker_3_second);

        wv_year.setGravity(gravity);
        wv_month.setGravity(gravity);
        wv_day.setGravity(gravity);
        wv_hours.setGravity(gravity);
        wv_minutes.setGravity(gravity);
        wv_seconds.setGravity(gravity);

        // 设置居中字体大小
        wv_year.setTextSize(textSize);
        wv_month.setTextSize(textSize);
        wv_day.setTextSize(textSize);
        wv_hours.setTextSize(textSize);
        wv_minutes.setTextSize(textSize);
        wv_seconds.setTextSize(textSize);

        // 设置标签
        wv_year.setLabel(getContext().getString(R.string.year));
        wv_month.setLabel(getContext().getString(R.string.month));
        wv_day.setLabel(getContext().getString(R.string.day));
        wv_hours.setLabel(getContext().getString(R.string.hours));
        wv_minutes.setLabel(getContext().getString(R.string.minutes));
        wv_seconds.setLabel(getContext().getString(R.string.seconds));

        // 设置文字偏移
        wv_day.setTextXOffset(0);
        wv_month.setTextXOffset(0);
        wv_year.setTextXOffset(0);
        wv_hours.setTextXOffset(0);
        wv_minutes.setTextXOffset(0);
        wv_seconds.setTextXOffset(0);

        // 设置是否循环滚动
        wv_year.setCyclic(true);
        wv_month.setCyclic(true);
        wv_day.setCyclic(true);
        wv_hours.setCyclic(true);
        wv_minutes.setCyclic(true);
        wv_seconds.setCyclic(true);

        // 设置分割线的颜色
        wv_day.setDividerColor(Color.YELLOW);
        wv_month.setDividerColor(Color.YELLOW);
        wv_year.setDividerColor(Color.YELLOW);
        wv_hours.setDividerColor(Color.YELLOW);
        wv_minutes.setDividerColor(Color.YELLOW);
        wv_seconds.setDividerColor(Color.YELLOW);

        // 设置分割线的类型
        wv_day.setDividerType(WheelView.DividerType.FILL);
        wv_month.setDividerType(WheelView.DividerType.FILL);
        wv_year.setDividerType(WheelView.DividerType.FILL);
        wv_hours.setDividerType(WheelView.DividerType.FILL);
        wv_minutes.setDividerType(WheelView.DividerType.FILL);
        wv_seconds.setDividerType(WheelView.DividerType.FILL);

        // 设置行距乘数
        wv_day.setLineSpacingMultiplier(lineSpacingMultiplier);
        wv_month.setLineSpacingMultiplier(lineSpacingMultiplier);
        wv_year.setLineSpacingMultiplier(lineSpacingMultiplier);
        wv_hours.setLineSpacingMultiplier(lineSpacingMultiplier);
        wv_minutes.setLineSpacingMultiplier(lineSpacingMultiplier);
        wv_seconds.setLineSpacingMultiplier(lineSpacingMultiplier);

        //  设置越界字体颜色
        wv_day.setTextColorOut(textColorOut);
        wv_month.setTextColorOut(textColorOut);
        wv_year.setTextColorOut(textColorOut);
        wv_hours.setTextColorOut(textColorOut);
        wv_minutes.setTextColorOut(textColorOut);
        wv_seconds.setTextColorOut(textColorOut);

        // 设置 居中 字体颜色
        wv_day.setTextColorCenter(textColorCenter);
        wv_month.setTextColorCenter(textColorCenter);
        wv_year.setTextColorCenter(textColorCenter);
        wv_hours.setTextColorCenter(textColorCenter);
        wv_minutes.setTextColorCenter(textColorCenter);
        wv_seconds.setTextColorCenter(textColorCenter);

        // 是否只显示中间选中项的
        wv_day.isCenterLabel(isCenterLabel);
        wv_month.isCenterLabel(isCenterLabel);
        wv_year.isCenterLabel(isCenterLabel);
        wv_hours.isCenterLabel(isCenterLabel);
        wv_minutes.isCenterLabel(isCenterLabel);
        wv_seconds.isCenterLabel(isCenterLabel);

        setTime();
    }

    public void createDialog() {
        if (dialogView != null) {
            mDialog = new Dialog(getContext(), R.style.custom_dialog2);
            mDialog.setCancelable(false);
            mDialog.setContentView(dialogView);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(R.style.pickerview_dialogAnim);
                dialogWindow.setGravity(Gravity.CENTER);
            }
        }
    }

    public Animation getInAnimation() {
        int res = PickerViewAnimateUtil.getAnimationResource(this.animGravity, true);
        return AnimationUtils.loadAnimation(getContext(), res);
    }

    public Animation getOutAnimation() {
        int res = PickerViewAnimateUtil.getAnimationResource(this.animGravity, false);
        return AnimationUtils.loadAnimation(getContext(), res);
    }

    /**
     * 设置选中时间,默认选中当前时间
     */
    private void setTime() {
        int year, month, day, hours, minute, seconds;
        Calendar calendar = Calendar.getInstance();

        if (date == null) {
            calendar.setTimeInMillis(System.currentTimeMillis());
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            hours = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
            seconds = calendar.get(Calendar.SECOND);
        } else {
            year = date.get(Calendar.YEAR);
            month = date.get(Calendar.MONTH);
            day = date.get(Calendar.DAY_OF_MONTH);
            hours = date.get(Calendar.HOUR_OF_DAY);
            minute = date.get(Calendar.MINUTE);
            seconds = date.get(Calendar.SECOND);
        }

        setPicker(year, month, day, hours, minute, seconds);
    }

    /**
     * 设置 日期 范围
     *
     * @param startDate
     * @param endDate
     */
    public void setRangDate(Calendar startDate, Calendar endDate) {
        if (startDate == null && endDate != null) {
            int year = endDate.get(Calendar.YEAR);
            int month = endDate.get(Calendar.MONTH) + 1;
            int day = endDate.get(Calendar.DAY_OF_MONTH);
            if (year > startYear) {
                this.endYear = year;
                this.endMonth = month;
                this.endDay = day;
            } else if (year == startYear) {
                if (month > startMonth) {
                    this.endYear = year;
                    this.endMonth = month;
                    this.endDay = day;
                } else if (month == startMonth) {
                    if (day > startDay) {
                        this.endYear = year;
                        this.endMonth = month;
                        this.endDay = day;
                    }
                }
            }
        } else if (startDate != null && endDate == null) {
            int year = startDate.get(Calendar.YEAR);
            int month = startDate.get(Calendar.MONTH) + 1;
            int day = startDate.get(Calendar.DAY_OF_MONTH);
            if (year < endYear) {
                this.startMonth = month;
                this.startDay = day;
                this.startYear = year;
            } else if (year == endYear) {
                if (month < endMonth) {
                    this.startMonth = month;
                    this.startDay = day;
                    this.startYear = year;
                } else if (month == endMonth) {
                    if (day < endDay) {
                        this.startMonth = month;
                        this.startDay = day;
                        this.startYear = year;
                    }
                }
            }
        } else if (startDate != null && endDate != null) {
            this.startYear = startDate.get(Calendar.YEAR);
            this.endYear = endDate.get(Calendar.YEAR);
            this.startMonth = startDate.get(Calendar.MONTH) + 1;
            this.endMonth = endDate.get(Calendar.MONTH) + 1;
            this.startDay = startDate.get(Calendar.DAY_OF_MONTH);
            this.endDay = endDate.get(Calendar.DAY_OF_MONTH);
        }
    }

    public void setPicker(int year, final int month, int day, int h, int m, int s) {
        int[] lunar = LunarCalendar.solarToLunar(year, month + 1, day);
        setLunar(lunar[0], lunar[1] - 1, lunar[2], lunar[3] == 1, h, m, s);
    }

    /**
     * 设置农历
     *
     * @param year
     * @param month
     * @param day
     * @param h
     * @param m
     * @param s
     */
    private void setLunar(int year, final int month, int day, boolean isLeap, int h, int m, int s) {
        // 年
        wv_year.setAdapter(new ArrayWheelAdapter(ChinaDate.getYears(startYear, endYear)));// 设置"年"的显示数据
        wv_year.setLabel("");// 添加文字
        wv_year.setCurrentItem(year - startYear);// 初始化时显示的数据

        // 月
        wv_month.setAdapter(new ArrayWheelAdapter(ChinaDate.getMonths(year)));
        wv_month.setLabel("");
        wv_month.setCurrentItem(month);

        // 日
        // 判断大小月及是否闰年,用来确定"日"的数据
        if (ChinaDate.leapMonth(year) == 0) {
            wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.monthDays(year, month))));
        } else {
            wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.leapDays(year))));
        }
        wv_day.setLabel("");
        wv_day.setCurrentItem(day - 1);

        wv_hours.setAdapter(new NumericWheelAdapter(0, 23));
        wv_hours.setCurrentItem(h);

        wv_minutes.setAdapter(new NumericWheelAdapter(0, 59));
        wv_minutes.setCurrentItem(m);

        wv_seconds.setAdapter(new NumericWheelAdapter(0, 59));
        wv_seconds.setCurrentItem(m);

        // 添加"年"监听
        wv_year.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                int year_num = index + startYear;
                // 判断是不是闰年,来确定月和日的选择
                wv_month.setAdapter(new ArrayWheelAdapter(ChinaDate.getMonths(year_num)));
                if (ChinaDate.leapMonth(year_num) != 0 && wv_month.getCurrentItem() > ChinaDate.leapMonth(year_num) - 1) {
                    wv_month.setCurrentItem(wv_month.getCurrentItem() + 1);
                } else {
                    wv_month.setCurrentItem(wv_month.getCurrentItem());
                }

                int maxItem = 29;
                if (ChinaDate.leapMonth(year_num) != 0 && wv_month.getCurrentItem() > ChinaDate.leapMonth(year_num) - 1) {
                    if (wv_month.getCurrentItem() == ChinaDate.leapMonth(year_num) + 1) {
                        wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.leapDays(year_num))));
                        maxItem = ChinaDate.leapDays(year_num);
                    } else {
                        wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.monthDays(year_num, wv_month.getCurrentItem()))));
                        maxItem = ChinaDate.monthDays(year_num, wv_month.getCurrentItem());
                    }
                } else {
                    wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.monthDays(year_num, wv_month.getCurrentItem() + 1))));
                    maxItem = ChinaDate.monthDays(year_num, wv_month.getCurrentItem() + 1);
                }

                if (wv_day.getCurrentItem() > maxItem - 1) {
                    wv_day.setCurrentItem(maxItem - 1);
                }
            }
        });

        // 添加"月"监听
        wv_month.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                int month_num = index;
                int year_num = wv_year.getCurrentItem() + startYear;
                int maxItem = 29;
                if (ChinaDate.leapMonth(year_num) != 0 && month_num > ChinaDate.leapMonth(year_num) - 1) {
                    if (wv_month.getCurrentItem() == ChinaDate.leapMonth(year_num) + 1) {
                        wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.leapDays(year_num))));
                        maxItem = ChinaDate.leapDays(year_num);
                    } else {
                        wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.monthDays(year_num, month_num))));
                        maxItem = ChinaDate.monthDays(year_num, month_num);
                    }
                } else {
                    wv_day.setAdapter(new ArrayWheelAdapter(ChinaDate.getLunarDays(ChinaDate.monthDays(year_num, month_num + 1))));
                    maxItem = ChinaDate.monthDays(year_num, month_num + 1);
                }

                if (wv_day.getCurrentItem() > maxItem - 1) {
                    wv_day.setCurrentItem(maxItem - 1);
                }
            }
        });

        wv_day.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
            }
        });

        wv_hours.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
            }
        });

        wv_minutes.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
            }
        });
        wv_seconds.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
            }
        });
    }

    /**
     * 重新设置日
     *
     * @param year_num
     * @param monthNum
     * @param startD
     * @param endD
     * @param list_big
     * @param list_little
     */
    private void setReDay(int year_num, int monthNum, int startD, int endD, List<String> list_big, List<String> list_little) {
        int currentItem = wv_day.getCurrentItem();

        if (list_big.contains(String.valueOf(monthNum))) {
            if (endD > 31) {
                endD = 31;
            }
            wv_day.setAdapter(new NumericWheelAdapter(startD, endD));
        } else if (list_little.contains(String.valueOf(monthNum))) {
            if (endD > 30) {
                endD = 30;
            }
            wv_day.setAdapter(new NumericWheelAdapter(startD, endD));
        } else {
            if ((year_num % 4 == 0 && year_num % 100 != 0)
                    || year_num % 400 == 0) {
                if (endD > 29) {
                    endD = 29;
                }
                wv_day.setAdapter(new NumericWheelAdapter(startD, endD));
            } else {
                if (endD > 28) {
                    endD = 28;
                }
                wv_day.setAdapter(new NumericWheelAdapter(startD, endD));
            }
        }

        if (currentItem > wv_day.getAdapter().getItemsCount() - 1) {
            currentItem = wv_day.getAdapter().getItemsCount() - 1;
            wv_day.setCurrentItem(currentItem);
        }
    }

    /**
     * 农历返回对应的公历时间
     */
    private String getLunarTime() {
        StringBuilder sb = new StringBuilder();
        int year = wv_year.getCurrentItem() + startYear;
        int month = 1;
        boolean isLeapMonth = false;
        if (ChinaDate.leapMonth(year) == 0) {
            month = wv_month.getCurrentItem() + 1;
        } else {
            if ((wv_month.getCurrentItem() + 1) - ChinaDate.leapMonth(year) <= 0) {
                month = wv_month.getCurrentItem() + 1;
            } else if ((wv_month.getCurrentItem() + 1) - ChinaDate.leapMonth(year) == 1) {
                month = wv_month.getCurrentItem();
                isLeapMonth = true;
            } else {
                month = wv_month.getCurrentItem();
            }
        }
        int day = wv_day.getCurrentItem() + 1;
        int[] solar = LunarCalendar.lunarToSolar(year, month, day, isLeapMonth);

        sb.append(solar[0]).append("-")
                .append(solar[1]).append("-")
                .append(solar[2]).append(" ")
                .append(wv_hours.getCurrentItem()).append(":")
                .append(wv_minutes.getCurrentItem()).append(":")
                .append(wv_seconds.getCurrentItem());
        return sb.toString();
    }

    public void showDialog() {
        if (mDialog != null) {
            mDialog.show();
        }
    }

    public void dismissDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dlg_picker_3_close:
                dismissDialog();
                break;
            case R.id.dlg_picker_3_btn:
                _logd("选择时间： " + getLunarTime());
                dismissDialog();
                break;
            default:
                break;
        }
    }

    private void _logd(String msg) {
        MyLog.logd("时钟选择器3 : " + msg);
    }
}
